#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRegularExpression>
#include <QDateTime>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QValueAxis>
#include <csignal>  // 添加这个头文件
#include <QNetworkInterface>  // 网络接口相关
#include <QHostAddress>       // IP地址处理
#include <QDebug>

void MainWindow::handleCommand302(const QMap<QString, QString> &params, QTcpSocket *client)
{
    // 1. 参数校验
    if (!params.contains("CamID") || !params.contains("IMAGENAME") ||
        !params.contains("TIME") || !params.contains("EXP_TYPE") ||
        !params.contains("IMG_INFO")) {
        sendResponse("<ID=302><INFO=Error><MSG=Missing_parameters>", client);
        return;
    }

    // 2. 检查相机状态
    if (cameraState.status != Idle) {
        //sendResponse("<ID=302><INFO=Error><MSG=Camera is busy>", client);
        //return;
    }

    // 3. 解析参数
    QString camId = params["CamID"];
    QString imageName = params["IMAGENAME"];
    double expTime = params["TIME"].toDouble();
    QString expType = params["EXP_TYPE"];
    QString imgInfo = params["IMG_INFO"];
    bool dump = params.value("DUMP", "0") == "1";
    bool pinning = params.value("PINNING", "0") == "1";


    int index = -1;
    if (expType == "sc") {
        index = ui->comBoxframetype->findData("sc");
    } else if (expType == "bs") {
        index = ui->comBoxframetype->findData("bs");
    } else if (expType == "dk") {
        index = ui->comBoxframetype->findData("dk");
    } else if (expType == "ts") {
        index = ui->comBoxframetype->findData("ts");
    } else if (expType == "sf") {
        index = ui->comBoxframetype->findData("sf");
    } else if (expType == "df") {
        index = ui->comBoxframetype->findData("df");
    } else if (expType == "fs") {
        index = ui->comBoxframetype->findData("fs");
    }
    if (index != -1) {
        QMetaObject::invokeMethod(this, [this, index]() {
            ui->comBoxframetype->setCurrentIndex(index);
        }, Qt::QueuedConnection);
    }

    // 4. 立即返回确认响应
    sendResponse("<ID=302><INFO=OK>", client);

    // 5. 记录曝光开始时间（ISO 8601格式）
    QDateTime expStartTime = QDateTime::currentDateTime();
    QString expStartTimeStr = expStartTime.toString("yyyy-MM-dd hh:mm:ss.zzz");

    // 6. 设置曝光参数
    currentBaseFilename = imageName;
    ui->lineEditBaseFilename->setText(currentBaseFilename);
    ui->doubleSpinBoxExposureTime->setValue(expTime);
    currentExposureTime = expTime;
    currentProgressTotalTime = expTime + 10; // 曝光+读出时间估算
    progressStartTime = QDateTime::currentMSecsSinceEpoch();

    // 7. 解析并保存IMG_INFO
    QJsonParseError jsonError;
    QJsonDocument doc = QJsonDocument::fromJson(imgInfo.toUtf8(), &jsonError);
    if (!doc.isNull() && doc.isObject()) {
        QJsonObject imgInfoObj = doc.object();
        if (imgInfoObj.contains("IMG_NUM")) {
            // 更新UI中的IMG_NUM显示
            QString imgNum = imgInfoObj["IMG_NUM"].toString();
            ui->lineEditImgNum->setText(imgNum);
            QString objectname = imgInfoObj["OBJ_NAME"].toString();
            ui->lineEditObjName->setText(objectname);
            QString fwname = imgInfoObj["FW_NAME"].toString();
            ui->lineEditFwName->setText(fwname);
            // 同时更新本地计数器，保持同步
            m_localImageCounter = imgNum.toInt();
        }
        hwStatus.currentImgInfo = imgInfoObj;
    } else {
        LOG_CAMERA(QString("IMG_INFO Parsing failed: %1").arg(jsonError.errorString()));
    }

    int darkMode = (expType == "bs" || expType == "dk") ? 1 : 0;

    // 8. 发送相机曝光指令（通过UDP）
    QString tag = QDateTime::currentDateTime().toString("yyMMddhhmmss");
    QString expCmd = QString("get_frame_290:$tag=%1$dark=%2$pinning=%3$dump=%4$exp=%5")
                         .arg(tag)
                         .arg(darkMode)  // 暗场标记
                         .arg(pinning ? 1 : 0)
                         .arg(dump ? 1 : 0)
                         .arg(expTime, 0, 'f', 2);
    sendCameraCommand(expCmd);

    // 存储响应信息
    QString tag1 = QDateTime::currentDateTime().toString("yyMMddhhmmss");
    m_pendingResponse = {
        client,
        params["CamID"],
        params["TIME"].toDouble(),
        QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"),
        params["IMAGENAME"]
    };

    // 9. 更新状态
    //hwStatus.cameraState = Exposing;
    //progressTimer->start();
    // 初始化进度控制
    currentPhase = PHASE_EXPOSING;
    progressStartTime = QDateTime::currentMSecsSinceEpoch();
    currentExposureTime = expTime;

    // 设置进度条范围
    ui->ExposureprogressBar->setRange(0, 100);
    ui->ExposureprogressBar->setValue(0);

    // 启动定时器
    progressTimer->start(200); // 200ms更新一次

    // 10. 记录日志
    LOG_CAMERA(QString("Start exposure [Cam:%1][Exp:%2s][Type:%3][File:%4]")
                    .arg(camId).arg(expTime).arg(expType).arg(imageName));

}